/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number[]}
 */
var intersect = function (nums1, nums2) {
  let map = new Map();
  nums1.forEach((num) => {
    let val = map.get(num) || 0;
    map.set(num, val + 1);
  });
  let res = [];
  nums2.forEach((num) => {
    let val = map.get(num) || 0;
    if (val !== 0) {
      map.set(num, val - 1);
      res.push(num);
    }
  });
  return res;
};
